package com.situ.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.entity.Course;
import com.situ.web.service.CourseService;

@WebServlet("/course")
public class CourseServlet extends HttpServlet{
	private CourseService courseService = new CourseService();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");
		
		// 如果没有传递method参数，默认执行查找所有
		if (method == null || "".equals(method)) {
			method = "findAll";
		}
		switch (method) {
		case "findAll":
			findAll(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		default:
			break;
		}
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		
		// 调用Service层的方法完成删除，而且返回要告诉我到底是成功了还是失败
		boolean isSuccess = courseService.deleteById(Integer.parseInt(id));
		
		resp.sendRedirect(req.getContextPath() + "/course?method=findAll");
	}

	private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Course> list = courseService.findAll();
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("course_list.jsp").forward(req, resp);
	}
}
